<template>
  <div class="accountContainer">
    <div class="head">登录密码设置</div>
    <el-form ref="form" :model="form" label-width="100px" :rules="rules">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="form.oldPassword" auto-complete="new-password"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" auto-complete="new-password"></el-input>
      </el-form-item>
      <el-form-item label="重输新密码" prop="newNewPassword">
        <el-input v-model="form.newNewPassword" auto-complete="new-password"></el-input>
      </el-form-item>
    </el-form>
    <div class="buttonGroup">
      <el-button @click="reset">重置</el-button>
      <el-button @click="submit">提交</el-button>
    </div>
  </div>
</template>

<script>
export default {
  created () {
    this.$bus.$emit('profile', 2)
  },
  data () {
    var confirmPassword = (rule, value, cb) => {
      if (value !== this.form.newPassword) {
        return cb(new Error('请保证密码和上面输入的一致!'))
      } else {
        cb()
      }
    }
    return {
      rules: {
        oldPassword: [ { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15个字符之间', trigger: 'blur' }],
        newPassword: [ { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15个字符之间', trigger: 'blur' }],
        newNewPassword: [{ required: true, message: '请确认输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15个字符之间', trigger: 'blur' },
          {validator: confirmPassword, trigger: 'blur'}]
      },
      form: {
        oldPassword: '',
        newPassword: '',
        newNewPassword: ''
      }
    }
  },
  methods: {
    reset () {
      this.$refs.form.resetFields()
    },
    submit () {
      this.$refs.form.validate(async (res) => {
        if (res === true) {
          const res = await this.$http.post('/users/updatePassword', this.form)
          this.$refs.form.resetFields()
          if (res.data.status === 999) {
            return this.$message.error('原密码错误，请重新输入~')
          } else {
            this.$message.success('修改密码成功~')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
  .buttonGroup {
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .accountContainer{
    padding: 10px;
  }
  .head{
    padding: 5px;
    border-bottom: 1px solid #888;
  }
  .el-form{
    margin: 10px 0 10px 200px;
  }
  .el-input{
    width: 200px;
  }

</style>
